package com.springcloud.sc.ucpv5.task;


import com.springcloud.sc.ucp.v5.api.entity.JobUcpSchedule;
import com.springcloud.sc.ucp.v5.api.entity.UcpServerInfo;
import com.springcloud.sc.ucpv5.service.JobUcpScheduleService;

import com.springcloud.sc.ucpv5.service.UcpServerInfoService;
import com.springcloud.sc.ucpv5.service.UcpService;
import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.ConnectException;
import java.util.*;

/**
 * 该方法用于对UCP操作后，将操作记录发送出去
 */

@Component
public class SchedulerTask {

    @Autowired
    private JobUcpScheduleService jobUcpScheduleService;


    /*@Autowired
    private UcpServerInfoService ucpServerInfoService;*/

    @Autowired
    private UcpService ucpService;

    @Value("${spring.voip.web.url}")
    private String voip_web_url;

    private int count=0;
    @Scheduled(cron="*/30 * * * * ?")
    private void process(){
        List<JobUcpSchedule> list = jobUcpScheduleService.getListByUnsent();
        /*UcpServerInfo ucpServerInfo = ucpServerInfoService.getEntityServerByFlag(voip_web_url );
        String ipURL = null;
        if(ucpServerInfo!=null){
            ipURL =  ucpServerInfo.getUcpIp();
        }*/
        if(!list.isEmpty()){
            for (JobUcpSchedule jobUcp : list ){
                String url = voip_web_url + jobUcp.getJobName();
                String result = doPost( url , jobUcp.getExecutionSource() );
                JSONObject jsonObject = null;
                if(!result.equals("")){
                    jsonObject= new JSONObject( result );
                    String result_code = String.valueOf( jsonObject.get("result_code") );
                    if(result_code.equals("0")){
                        jobUcp.setIsSuccess(1);
                        jobUcp.setCompleteTime( new Date() );
                        jobUcpScheduleService.updateEntity( jobUcp );
                    }
                }
             }
        }
    }

    @Scheduled(cron="*/60 * * * * ?")
    public void processUcp(){
        ucpService.getAllUserInfoListTreeByGroup();
    }


    public static String doPost(String url, String json ) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;

//        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/json");
        // 封装json请求参数
        try {

            StringEntity requestEntity = new StringEntity(json,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
//            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity( requestEntity );

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);

//            result = httpClient.execute(httpPost,responseHandler);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }catch(ConnectException connectException){
            System.out.println("与来讯的Web接口连接异常.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
